package com.joolun.mall.service.impl;

import cn.hutool.core.util.IdUtil;
import com.google.common.collect.Lists;
import com.joolun.common.core.domain.AjaxResult;
import com.joolun.mall.constant.MallConstants;
import com.joolun.mall.dto.*;
import com.joolun.mall.entity.OrderInfo;
import com.joolun.mall.entity.UserAddress;
import com.joolun.mall.handle.LogisticsAbstractHandler;
import com.joolun.mall.service.LogisticsService;
import com.joolun.mall.service.OrderInfoService;
import com.joolun.mall.service.UserAddressService;
import com.joolun.weixin.constant.MyReturnCode;
import com.joolun.weixin.utils.ThirdSessionHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

/**
 * @author quyang
 * @description
 * @date 2022/1/2
 */
@Slf4j
@Service
public class LogisticsServiceImpl implements LogisticsService {

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private UserAddressService userAddressService;

    @Autowired
    private LogisticsAbstractHandler logisticsAbstractHandler;

    @Override
    public List<JDFreightResultDTO> queryEstimatedFreights(JDEstimatedFreightsParamDTO body) {

        UserAddress senderAddress = userAddressService.getById(body.getSenderAddressId());
        Assert.notNull(senderAddress, "发货地址不存在");
        UserAddress receiverAddress = userAddressService.getById(body.getReceiverAddressId());
        Assert.notNull(receiverAddress, "收货地址不存在");

        LogisticsAbstractHandler logisticsHandler = logisticsAbstractHandler.getInstance(body.getLogisticsId());
        List<JDFreightResultDTO> freights = logisticsHandler.freight(senderAddress, receiverAddress, body.getWeight());
        return freights;
    }

    @Override
    public AjaxResult delivery(JDDeliveryParamDTO body) {
        UserAddress senderAddress = userAddressService.getById(body.getSenderAddressId());
        Assert.notNull(senderAddress, "发货地址不存在");
        UserAddress receiverAddress = userAddressService.getById(body.getReceiverAddressId());
        Assert.notNull(receiverAddress, "收货地址不存在");

        //下单产生订单号
        PlaceOrderDTO placeOrderDTO = new PlaceOrderDTO();
        placeOrderDTO.setDeliveryWay(body.getLogisticsId().toString());
        //placeOrderDTO.setUserId(ThirdSessionHolder.getWxUserId());
        placeOrderDTO.setUserId(body.getUserId());
        placeOrderDTO.setPaymentWay(MallConstants.PAYMENT_WAY_2);
        placeOrderDTO.setUserMessage("顺丰快递单");
        placeOrderDTO.setUserAddressId(receiverAddress.getId());

        OrderInfo orderInfo = orderInfoService.orderSubLogistics(placeOrderDTO);
        if (orderInfo == null) {
            return AjaxResult.error(MyReturnCode.ERR_70005.getCode(), MyReturnCode.ERR_70005.getMsg());
        }

        JDEstimatedFreightsParamDTO freightsParamDTO = new JDEstimatedFreightsParamDTO();
        freightsParamDTO.setLogisticsId(body.getLogisticsId());
        freightsParamDTO.setWeight(body.getWeight());
        freightsParamDTO.setReceiverAddressId(body.getReceiverAddressId());
        freightsParamDTO.setSenderAddressId(body.getSenderAddressId());
        List<JDFreightResultDTO> jdFreightResultDTOS = queryEstimatedFreights(freightsParamDTO);
        Optional<JDFreightResultDTO> first = jdFreightResultDTOS.stream().filter(m -> m.getChannelCode().equals(body.getChannelCode())).findFirst();
        if (first.isPresent()){
            JDFreightResultDTO freightResultDTO = first.get();
            BigDecimal freight = freightResultDTO.getFreight();
            orderInfo.setFreightPrice(freight);
            orderInfo.setPaymentPrice(freight);
            orderInfoService.updateById(orderInfo);
        }else {
            return AjaxResult.error("无法获取运费, 请重试");
        }

        //Long orderId = IdUtil.getSnowflake(1, 1).nextId();
        String orderId = orderInfo.getId();
        LogisticsAbstractHandler logisticsHandler = logisticsAbstractHandler.getInstance(body.getLogisticsId());
        AjaxResult deliveryResult = logisticsHandler.delivery(senderAddress, receiverAddress, body.getWeight(), orderId, body.getChannelCode());
        if (deliveryResult.isSuccess()) {
            String waybillNo = (String) deliveryResult.getData();
            orderInfo.setLogisticsNo(waybillNo);
            orderInfoService.updateById(orderInfo);
        }
        return AjaxResult.success(orderInfo);
    }

    @Override
    public JDCancelOrderResultDTO cancelOrder(Integer logisticsId, String deliveryNo) {
        LogisticsAbstractHandler logisticsHandler = logisticsAbstractHandler.getInstance(logisticsId);
        JDCancelOrderResultDTO result = logisticsHandler.cancelOrder(deliveryNo);
        return result;
    }
}
